package wang.jinggo.cryptto;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

/**
 * 秘钥的生成
 *
 * @author wangyj
 * @description
 * @create 2017-06-26 9:29
 **/
public class GenerateKeyPair {

    private final static Logger LOG =  LoggerFactory.getLogger(GenerateKeyPair.class);
    public String priKey;
    public String pubKey;

    public void run(){
        try {
            KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
            SecureRandom secrand = new SecureRandom();
            secrand.setSeed("ecs".getBytes()); // 初始化随机产生器
            keygen.initialize(1024, secrand);
            KeyPair keys = keygen.genKeyPair();

            PublicKey pubkey = keys.getPublic();
            PrivateKey prikey = keys.getPrivate();

            pubKey = bytesToHexStr(pubkey.getEncoded());
            priKey = bytesToHexStr(prikey.getEncoded());

            LOG.info("pubKey================>{}", pubKey);
            LOG.info("priKey================>{}", priKey);
            LOG.info("写入对象 pubkeys ok");
            LOG.info("生成密钥对成功");

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            LOG.error("生成密钥对失败",e.getMessage());
        }
    }

    public static String getKeyByHmac(String keyParam){
        String keyStr = "";
        try {
            //其他可以是HmacSHA1,HmacSHA256 等
            KeyGenerator keygen = KeyGenerator.getInstance("HmacMD5");
            SecretKey key = keygen.generateKey();

            byte[] keyBytes = key.getEncoded();
            keyStr = encryptHmac(keyBytes, "Hello".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("生成Hmac 密钥对失败",e.getMessage());
        }
        return keyStr;
    }

    public static String encryptHmac(byte[] key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {
        SecretKey secretKey = new SecretKeySpec(key, "HmacMD5");
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(secretKey);

        byte[] resultBytes = mac.doFinal();
        String resultString = bytesToHexStr(resultBytes);

        return resultString;
    }


    /**
     * Transform the specified byte into a Hex String form.
     */
    public static final String bytesToHexStr(byte[] bcd) {
        StringBuffer s = new StringBuffer(bcd.length * 2);

        for (int i = 0; i < bcd.length; i++) {
            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
            s.append(bcdLookup[bcd[i] & 0x0f]);
        }

        return s.toString();
    }

    /**
     * Transform the specified Hex String into a byte array.
     */
    public static final byte[] hexStrToBytes(String s) {
        byte[] bytes;
        bytes = new byte[s.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
                    16);
        }
        return bytes;
    }

    private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    //b7b2c13fc1478d27e7d9a9b68964dd87
    public static void main(String[] args) {
        String keyParam = "sfkey12345";
        String kk = getKeyByHmac(keyParam);
        System.out.println("GenerateKeyPair.main:" + kk);
    }
}
